<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
    width="500px"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="头像" prop="avatar" class="avatar-form-item">
        <div class="avatar-content">
          <ElUpload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <ElIcon v-else class="avatar-uploader-icon"><Plus /></ElIcon>
          </ElUpload>
          <div class="el-upload__tip">支持jpg/png格式，大小不超过2MB</div>
        </div>
      </ElFormItem>

      <ElFormItem label="名称" prop="name">
        <ElInput v-model="formData.name" placeholder="请输入用户名称" />
      </ElFormItem>

      <ElFormItem label="手机号" prop="phone">
        <ElInput v-model="formData.phone" placeholder="请输入手机号" maxlength="11" />
      </ElFormItem>

      <ElFormItem v-if="dialogType === 'add'" label="密码" prop="password">
        <ElInput
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </ElFormItem>

      <ElFormItem v-if="dialogType === 'add'" label="性别" prop="gender">
        <ElRadioGroup v-model="formData.gender">
          <ElRadio :label="0">未知</ElRadio>
          <ElRadio :label="1">男</ElRadio>
          <ElRadio :label="2">女</ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <ElFormItem v-if="dialogType === 'add'" label="注册来源" prop="registerSource">
        <ElRadioGroup v-model="formData.registerSource">
          <ElRadio label="app">APP</ElRadio>
          <ElRadio label="miniprogram">小程序</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">确定</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { Plus } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules, UploadProps } from 'element-plus'
  import { ElMessage } from 'element-plus'

  interface Props {
    visible: boolean
    type: string
    userData?: any
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    avatar: '',
    name: '',
    phone: '',
    password: '',
    gender: 0,
    registerSource: 'app'
  })

  // 表单验证规则
  const rules: FormRules = {
    name: [
      { required: true, message: '请输入用户名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
  }

  // 头像上传处理
  const handleAvatarChange: UploadProps['onChange'] = (uploadFile) => {
    if (uploadFile.raw) {
      formData.avatar = URL.createObjectURL(uploadFile.raw)
    }
  }

  // 初始化表单数据
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData

    Object.assign(formData, {
      avatar: isEdit ? row.avatar || '' : '',
      name: isEdit ? row.name || '' : '',
      phone: isEdit ? row.phone || '' : '',
      password: '',
      gender: isEdit ? row.gender || 0 : 0,
      registerSource: isEdit ? row.registerSource || 'app' : 'app'
    })
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate((valid) => {
      if (valid) {
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
        dialogVisible.value = false
        emit('submit')
      }
    })
  }
</script>

<style lang="scss" scoped>
  .avatar-form-item {
    :deep(.el-form-item__content) {
      align-items: flex-start;
    }
  }

  .avatar-content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
  }
</style>

